package stdio.costa.imoca.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Component;

import stdio.costa.imoca.model.Activity;

@Component
public class ActivityDao {

	@PersistenceContext
	private EntityManager entityManager;

	public void save(Activity activity) {
		entityManager.persist(activity);
	}

	public Activity update(Activity activity) {
		return entityManager.merge(activity);
	}

	public Activity findActivityByUuid(String uuid) {
		Query query = this.entityManager.createNamedQuery("findActivityByUuid")
				.setParameter("uuid", uuid);
		try {
			return (Activity) query.getSingleResult();
		} catch (NoResultException ne) {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Activity> findAllActivities() {
		Query query = this.entityManager.createNamedQuery("findAllActivities");
		try {
			return query.getResultList();
		} catch (NoResultException ne) {
			return null;
		}
	}
}
